package com.wyd.wenyongdaAdmin.admin.user.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wyd.wenyongdaAdmin.commons.model.admin.role.dto.RoleUserDTO;
import com.wyd.wenyongdaAdmin.commons.model.admin.role.entity.RoleUserEntity;
import com.wyd.wenyongdaAdmin.commons.model.admin.user.dto.UserAccountDTO;
import com.wyd.wenyongdaAdmin.commons.model.admin.user.dto.UserInfoDTO;
import com.wyd.wenyongdaAdmin.commons.model.admin.user.entity.UserAccountEntity;
import com.wyd.wenyongdaAdmin.commons.model.admin.user.vo.UserInfoVO;
import com.wyd.wenyongdaAdmin.commons.util.ResultEnum;
import com.wyd.wenyongdaAdmin.commons.util.ResultUtil;
import com.wyd.wenyongdaAdmin.xo.admin.role.service.IRoleUserService;
import com.wyd.wenyongdaAdmin.xo.admin.user.service.IUserAccountService;
import com.wyd.wenyongdaAdmin.xo.admin.user.service.IUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wenyongda
 * @since 2021-10-18
 */
@Api(tags = "用户中心")
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private IUserAccountService userAccountService;

    @Autowired
    public void setUserAccountService(IUserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    private IUserInfoService userInfoService;

    @Autowired
    public void setUserInfoService(IUserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    private IRoleUserService roleUserService;

    @Autowired
    public void setRoleUserService(IRoleUserService roleUserService) {
        this.roleUserService = roleUserService;
    }

    @ApiOperation("添加用户")
    @PostMapping("/save")
    public ResultUtil addUser(@RequestBody Map<String, Object> reqParams) {
        if (ObjectUtil.isNotNull(reqParams.get("username")) &&
        ObjectUtil.isNotNull(reqParams.get("nickName"))) {
            String username = (String) reqParams.get("username");
            String nickName = (String) reqParams.get("nickName");
            String phoneNumber = (String) reqParams.get("phoneNumber");
            Integer gender = (Integer) reqParams.get("gender");
            String email = (String) reqParams.get("email");
            String description = (String) reqParams.get("description");
            Integer addUserInfoRes = this.userInfoService.addUserInfo(new UserInfoDTO().setNickName(nickName)
                    .setPhoneNumber(phoneNumber).setGender(gender).setEmail(email).setDescription(description));
            Integer addUserAccountRes = this.userAccountService.addUserAccount(new UserAccountDTO().setUsername(username)
                    .setPassword("123456"));
            if (ObjectUtil.isNotNull(reqParams.get("roleId"))) {
                Long roleId = Long.valueOf(reqParams.get("roleId").toString());
                Long userId = this.userAccountService.getOne(new QueryWrapper<UserAccountEntity>().eq("username",username)).getId();
                Integer addUserRole = this.roleUserService.addRoleUser(new RoleUserDTO().setUserId(userId).setRoleId(roleId));
                if (addUserInfoRes!=0 && addUserAccountRes!=0 && addUserRole!=0) {
                    return ResultUtil.ok();
                } else {
                    return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
                }
            }
            if (addUserInfoRes!=0 && addUserAccountRes!=0) {
                return ResultUtil.ok();
            } else {
                return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
            }
        } else {
            return ResultUtil.error(ResultEnum.USERNAME_OR_NICKNAME_IS_EMPTY);
        }
    }

    @ApiOperation("分页查询用户列表")
    @PostMapping("/getAll")
    public ResultUtil selectUserPageWithCount(@RequestBody Map<String, Object> reqParams) {
        if (ObjectUtil.isNotNull(reqParams.get("pageNumber")) && ObjectUtil.isNotNull(reqParams.get("pageSize"))) {
            Integer pageNumber = (Integer) reqParams.get("pageNumber");
            Integer pageSize = (Integer) reqParams.get("pageSize");
            PageInfo<UserInfoVO> pageInfo = this.userInfoService.selectUserInfoVOPageWithCount(pageNumber, pageSize, userInfoVOIfHasStrBlankToNull(reqParams));
            return ResultUtil.ok().data("records",pageInfo);
        } else {
            return ResultUtil.error(ResultEnum.PAGE_NUMBER_OR_PAGE_SIZE_IS_EMPTY);
        }
    }


    @ApiOperation("更新用户")
    @PutMapping("/update")
    public ResultUtil updateUserInfo(@RequestBody Map<String, Object> reqParams) {
        if (ObjectUtil.isNotNull(reqParams.get("id"))) {
            UserInfoDTO userInfoDTO = BeanUtil.fillBeanWithMap(reqParams, new UserInfoDTO(), false);
            Integer updateUserInfoRes = this.userInfoService.updateUserInfo(userInfoDTO);
            if (ObjectUtil.isNotNull(reqParams.get("roleId"))) {
                Long roleId = Long.valueOf(reqParams.get("roleId").toString());
                Long userId = Long.valueOf(reqParams.get("id").toString());
                RoleUserEntity existRoleUser = this.roleUserService.getOne(new QueryWrapper<RoleUserEntity>().eq("user_id", userId));
                if (ObjectUtil.isNotNull(existRoleUser)) {
                    Integer updateUserRole = this.roleUserService.updateRoleUser(new RoleUserDTO().setRoleId(roleId).setUserId(userId));
                    if (updateUserRole > 0 && updateUserInfoRes > 0) {
                        return ResultUtil.ok();
                    } else {
                        return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
                    }
                } else {
                    Integer addUserRole = this.roleUserService.addRoleUser(new RoleUserDTO().setRoleId(roleId).setUserId(userId));
                    if (addUserRole > 0 && updateUserInfoRes > 0) {
                        return ResultUtil.ok();
                    } else {
                        return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
                    }
                }
            }
            if (updateUserInfoRes > 0) {
                return ResultUtil.ok();
            } else {
                return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
            }
        } else {
            return ResultUtil.error(ResultEnum.USER_ID_IS_EMPTY);
        }
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete")
    public ResultUtil deleteUser(@RequestBody Map<String, Object> reqParams) {
        if (ObjectUtil.isNotNull(reqParams.get("ids"))) {
            List<Long> ids = Convert.toList(Long.TYPE ,reqParams.get("ids"));
            if (this.userInfoService.deleteUserInfo(ids) > 0 &&
            this.userAccountService.deleteUserAccount(ids) > 0 &&
            this.roleUserService.deleteRoleUser(ids) > 0) {
                return ResultUtil.ok();
            } else {
                return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
            }
        } else {
            return ResultUtil.error(ResultEnum.USER_ID_IS_EMPTY);
        }
    }

    @ApiOperation("用户信息")
    @GetMapping("/info")
    public ResultUtil userInfo(@RequestParam Long id) {
        if (ObjectUtil.isNotNull(id)) {
            UserInfoVO userInfoVO = this.userInfoService.selectUserInfoVOById(id);
            return ResultUtil.ok().data("userInfo", userInfoVO);
        } else {
            return ResultUtil.error(ResultEnum.USER_ID_IS_EMPTY);
        }
    }

    @PutMapping("/reset/password")
    public ResultUtil resetUserAccountPassword(@RequestBody Map<String, Object> reqParams) {
        if (ObjectUtil.isNotNull(reqParams.get("id"))){
            UserAccountDTO userAccountDTO = new UserAccountDTO().setId(Long.valueOf(reqParams.get("id").toString()))
                    .setPassword("123456");
            Integer updateUserAccountRes = this.userAccountService.updateUserAccount(userAccountDTO);
            if (updateUserAccountRes > 0) {
                return ResultUtil.ok();
            } else {
                return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
            }
        } else {
            return ResultUtil.error(ResultEnum.USER_ID_IS_EMPTY);
        }
    }

    @PutMapping("/update/password")
    public ResultUtil updateUserAccountPassword(@RequestBody Map<String, Object> reqParams) {
        if (ObjectUtil.isNotNull(reqParams.get("id"))){
            Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(reqParams.get("params")));
            UserAccountEntity one = this.userAccountService.getOne(new QueryWrapper<UserAccountEntity>().eq("id", reqParams.get("id"))
                    .eq("password", params.get("oldPassword")));
            if (ObjectUtil.isNotNull(one)) {
                UserAccountDTO userAccountDTO = new UserAccountDTO().setId(Long.valueOf(reqParams.get("id").toString()))
                        .setPassword(String.valueOf(params.get("newPassword")));
                Integer updateUserAccountRes = this.userAccountService.updateUserAccount(userAccountDTO);
                if (updateUserAccountRes > 0) {
                    return ResultUtil.ok();
                } else {
                    return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
                }
            } else {
                return ResultUtil.error(ResultEnum.PASSWORD_ERROR);
            }

        } else {
            return ResultUtil.error(ResultEnum.USER_ID_IS_EMPTY);
        }
    }

    private UserInfoVO userInfoVOIfHasStrBlankToNull(Map<String, Object> reqParams) {
        UserInfoVO userInfoVO = new UserInfoVO();
        if (StrUtil.isNotBlank((String) reqParams.get("nickName"))) {
            String nickName = (String) reqParams.get("nickName");
            userInfoVO.setNickName(nickName);
        }
        if (StrUtil.isNotBlank((String) reqParams.get("username"))) {
            String username = (String) reqParams.get("username");
            userInfoVO.setUsername(username);
        }
        if (StrUtil.isNotBlank(String.valueOf(reqParams.get("isEnabled")))) {
            Integer isEnabled = (Integer) reqParams.get("isEnabled");
            userInfoVO.setIsEnabled(isEnabled);
        }
        return userInfoVO;
    }
}
